﻿#include "mainwindow.h"
#include <QFile>
#include <QApplication>
#include <QMessageBox>
#include <QJsonDocument>
#include <QJsonObject>
#include <QPushButton>
#include <QHBoxLayout>
#include <QFileDialog>
#include "question/singlechoicequestin.h"
#include "question/judgequestion.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
{
    setupUI();
    loadExam();
    // 加载样式表
    QFile styleFile(":/styles/ques/styles/style.qss");
    if (!styleFile.exists()) {
        // 如果资源文件不存在，尝试从文件系统加载
        styleFile.setFileName("styles/style.qss");
        qDebug() << u8"尝试从文件系统加载样式表: styles/style.qss";
    }

    if (styleFile.open(QIODevice::ReadOnly)) {
        QString style = QLatin1String(styleFile.readAll());
        qApp->setStyleSheet(style); // 应用于整个应用
        styleFile.close();
        qDebug() << u8"样式表加载成功";
        //qDebug() << QString(u8"样式表加载成功l");
    } else {
        qWarning() << u8"无法加载样式表l:" << styleFile.errorString();
    }

}

MainWindow::~MainWindow()
{
    delete m_examPaper;
}


void MainWindow::setupUI()
{
    // 创建中央部件
    QWidget *centralWidget = new QWidget(this);
    QVBoxLayout *mainLayout = new QVBoxLayout(centralWidget);

    // 创建标题栏
    QWidget *headerWidget = new QWidget(centralWidget);
    QVBoxLayout *headerLayout = new QVBoxLayout(headerWidget);

    m_titleLabel = new QLabel(headerWidget);
    m_titleLabel->setObjectName(u8"titleLabel"); // 设置对象名称，以便样式表可以通过ID选择器应用样式
    m_titleLabel->setAlignment(Qt::AlignCenter);

    m_studentLabel = new QLabel(headerWidget);
    m_studentLabel->setStyleSheet("font-size: 12pt;");
    m_studentLabel->setAlignment(Qt::AlignCenter);

    headerLayout->addWidget(m_titleLabel);
    headerLayout->addWidget(m_studentLabel);

    // 创建滚动区域
    m_scrollArea = new QScrollArea(centralWidget);
    m_scrollArea->setWidgetResizable(true);

    m_contentWidget = new QWidget(m_scrollArea);
    m_contentLayout = new QVBoxLayout(m_contentWidget);
    m_contentLayout->setAlignment(Qt::AlignTop);
    m_contentLayout->setSpacing(20);
    m_contentLayout->setContentsMargins(15, 15, 15, 15);

    m_scrollArea->setWidget(m_contentWidget);

    // 创建按钮栏
    QWidget *buttonWidget = new QWidget(centralWidget);
    QHBoxLayout *buttonLayout = new QHBoxLayout(buttonWidget);

    QPushButton *loadButton = new QPushButton(u8"加载试卷", buttonWidget);
    QPushButton *saveButton = new QPushButton(u8"保存答案", buttonWidget);
    QPushButton *exitButton = new QPushButton(u8"退出z",buttonWidget);
    buttonLayout->addStretch();
    buttonLayout->addWidget(loadButton);
    buttonLayout->addWidget(saveButton);
    buttonLayout->addWidget(exitButton);

    // 添加到主布局
    mainLayout->addWidget(headerWidget);
    mainLayout->addWidget(m_scrollArea, 1);
    mainLayout->addWidget(buttonWidget);

    setCentralWidget(centralWidget);
    resize(1000, 700);
    setWindowTitle(u8"试卷页面显示");

    // 连接信号
    connect(loadButton, &QPushButton::clicked, this, &MainWindow::loadExam);
    connect(saveButton, &QPushButton::clicked, this, &MainWindow::saveAnswers);
    connect(exitButton, &QPushButton::clicked, this, &QMainWindow::close);
    // 初始化状态
    //updateAnswerStatus();

}


//解析原始数据
void MainWindow::loadExam()
{
    // 使用文件对话框让用户选择文件
    QString filePath = QFileDialog::getOpenFileName(this, u8"打开试卷文件", "", u8"文本文件 (*.txt);;JSON文件 (*.json);;所有文件 (*.*)");
    if (filePath.isEmpty()) return;

    QFile file(filePath);
    if (!file.open(QIODevice::ReadOnly)) {
        QMessageBox::critical(this, u8"错误", u8"无法打开试卷文件: " + file.errorString());
        return;
    }

    QByteArray jsonData = file.readAll();
    file.close();

    QJsonDocument doc = QJsonDocument::fromJson(jsonData);
    if (doc.isNull()) {
        QMessageBox::critical(this, "错误", u8"试卷文件格式错误");
        return;
    }

    QJsonObject json = doc.object();
    // 创建试卷对象
    if (m_examPaper) {
        delete m_examPaper;
    }
    m_examPaper = new ExamPaper(this);

    //connect(m_examPaper, &ExamPaper::totalScoreChanged,this, &MainWindow::updateTotalScore);
    QApplication::setOverrideCursor(Qt::WaitCursor);
    bool success = m_examPaper->fromJson(json);
    QApplication::restoreOverrideCursor();

    if (success) {
        displayExam();
        QMessageBox::information(this, u8"成功", u8"试卷加载成功");
    } else {
        QMessageBox::critical(this, u8"错误", u8"试卷解析失败");
    }

}


void MainWindow::displayExam()
{
    clearDisplay();

    if (!m_examPaper) return;

    // 更新标题信息
    m_titleLabel->setText(m_examPaper->title());
    m_studentLabel->setText(QString(u8"学生: %1 (%2)")
                                .arg(m_examPaper->studentName())
                                .arg(m_examPaper->studentCode()));

    // 创建一个统一的内容容器，在这个容器中直接构建所有题目的UI
    QWidget *unifiedContentWidget = new QWidget(m_contentWidget);
    QVBoxLayout *unifiedLayout = new QVBoxLayout(unifiedContentWidget);
    unifiedLayout->setAlignment(Qt::AlignTop);
    unifiedLayout->setContentsMargins(20, 20, 20, 20);
    unifiedContentWidget->setObjectName("unifiedExamContent");

    // 获取所有题目
    QList<Question*> allQuestions = m_examPaper->questions();
    
    // 按题型将题目分组
    QList<Question*> singleChoiceQuestions;
    QList<Question*> judgeQuestions;
    
    for (Question *question : allQuestions) {
        if (question->typeId() == Question::TYPE_SINGLE_CHOICE) {
            singleChoiceQuestions.append(question);
        } else if (question->typeId() == Question::TYPE_JUDGE) {
            judgeQuestions.append(question);
        }
    }
    
    // 单选题部分
    if (!singleChoiceQuestions.isEmpty()) {
        // 创建单选题标题
        QLabel *singleChoiceTitle = new QLabel(u8"一、单选题", unifiedContentWidget);
        singleChoiceTitle->setObjectName("questionTypeTitle");
        singleChoiceTitle->setStyleSheet("font-size: 14pt; font-weight: bold; color: #2c3e50; margin-top: 10px; margin-bottom: 15px;");
        unifiedLayout->addWidget(singleChoiceTitle);
        
        // 为单选题直接在统一容器中构建UI
        int singleChoiceNum = 1;
        for (Question *question : singleChoiceQuestions) {
            qDebug() << u8"显示单选题:" << singleChoiceNum << u8"ID:" << question->id();
            
            // 直接构建题目UI到统一布局中
            // 添加题目编号和内容，确保编号与内容始终在同一行
            QWidget *questionContainer = new QWidget(unifiedContentWidget);
            QHBoxLayout *questionLayout = new QHBoxLayout(questionContainer);
            questionLayout->setContentsMargins(0, 0, 0, 0);
            questionLayout->setSpacing(5);
            
            // 题目编号标签
            QLabel *numberLabel = new QLabel(QString("%1.").arg(singleChoiceNum), unifiedContentWidget);
            numberLabel->setStyleSheet("font-size: 11pt; margin-bottom: 10px;");
            numberLabel->setFixedWidth(30); // 固定宽度，确保对齐
            numberLabel->setAlignment(Qt::AlignLeft | Qt::AlignTop);
            
            // 题目内容标签
            QLabel *contentLabel = new QLabel(question->stem(), unifiedContentWidget);
            contentLabel->setWordWrap(true);
            contentLabel->setStyleSheet("font-size: 11pt; margin-bottom: 10px;");
            contentLabel->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred);
            contentLabel->setAlignment(Qt::AlignLeft | Qt::AlignTop);
            
            // 添加到水平布局
            questionLayout->addWidget(numberLabel);
            questionLayout->addWidget(contentLabel, 1); // 内容标签占据剩余空间
            
            // 将容器添加到主布局
            unifiedLayout->addWidget(questionContainer);
            
            // 对于单选题，需要特殊处理选项
            if (dynamic_cast<SingleChoiceQuestin*>(question)) {
                SingleChoiceQuestin *singleChoice = static_cast<SingleChoiceQuestin*>(question);
                QVBoxLayout *optionsLayout = new QVBoxLayout();
                optionsLayout->setSpacing(8);
                QButtonGroup *buttonGroup = new QButtonGroup(unifiedContentWidget);
                
                // 创建选项按钮
                for (const auto &option : singleChoice->options()) {
                    QRadioButton *radioButton = new QRadioButton(
                        QString(u8"%1. %2").arg(option.code).arg(option.content),
                        unifiedContentWidget
                    );
                    radioButton->setProperty("optionId", option.id);
                    radioButton->setStyleSheet("font-size: 10pt; margin-left: 20px;");
                    buttonGroup->addButton(radioButton);
                    optionsLayout->addWidget(radioButton);
                    
                    // 如果这是用户答案，选中它
                    if (QString::number(option.id) == singleChoice->userAnswer()) {
                        radioButton->setChecked(true);
                    }
                }
                
                // 连接信号
                connect(buttonGroup, QOverload<QAbstractButton*>::of(&QButtonGroup::buttonClicked),
                        this, [=](QAbstractButton *button) {
                            singleChoice->setUserAnswer(QString::number(button->property("optionId").toInt()));
                        });
                
                // 添加选项布局到主布局
                QWidget *optionsWidget = new QWidget(unifiedContentWidget);
                optionsWidget->setLayout(optionsLayout);
                unifiedLayout->addWidget(optionsWidget);
            }
            
            // 添加题目间距
            unifiedLayout->addSpacing(20);
            singleChoiceNum++;
        }
    }
    
    // 判断题部分
    if (!judgeQuestions.isEmpty()) {
        // 创建判断题标题
        QLabel *judgeTitle = new QLabel(u8"二、判断题", unifiedContentWidget);
        judgeTitle->setObjectName("questionTypeTitle");
        judgeTitle->setStyleSheet("font-size: 14pt; font-weight: bold; color: #2c3e50; margin-top: 25px; margin-bottom: 15px;");
        unifiedLayout->addWidget(judgeTitle);
        
        // 为判断题直接在统一容器中构建UI
        int judgeNum = 1;
        for (Question *question : judgeQuestions) {
            qDebug() << u8"显示判断题:" << judgeNum << u8"ID:" << question->id();
            
            // 添加题目编号和内容，确保编号与内容始终在同一行
            QWidget *questionContainer = new QWidget(unifiedContentWidget);
            QHBoxLayout *questionLayout = new QHBoxLayout(questionContainer);
            questionLayout->setContentsMargins(0, 0, 0, 0);
            questionLayout->setSpacing(5);
            
            // 题目编号标签
            QLabel *numberLabel = new QLabel(QString("%1.").arg(judgeNum), unifiedContentWidget);
            numberLabel->setStyleSheet("font-size: 11pt; margin-bottom: 10px;");
            numberLabel->setFixedWidth(30); // 固定宽度，确保对齐
            numberLabel->setAlignment(Qt::AlignLeft | Qt::AlignTop);
            
            // 题目内容标签
            QLabel *contentLabel = new QLabel(question->stem(), unifiedContentWidget);
            contentLabel->setWordWrap(true);
            contentLabel->setStyleSheet("font-size: 11pt; margin-bottom: 10px;");
            contentLabel->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred);
            contentLabel->setAlignment(Qt::AlignLeft | Qt::AlignTop);
            
            // 添加到水平布局
            questionLayout->addWidget(numberLabel);
            questionLayout->addWidget(contentLabel, 1); // 内容标签占据剩余空间
            
            // 将容器添加到主布局
            unifiedLayout->addWidget(questionContainer);
            
            // 对于判断题，需要特殊处理选项
            if (dynamic_cast<JudgeQuestion*>(question)) {
                JudgeQuestion *judgeQuestion = static_cast<JudgeQuestion*>(question);
                QHBoxLayout *optionsLayout = new QHBoxLayout();
                optionsLayout->setSpacing(20);
                QButtonGroup *buttonGroup = new QButtonGroup(unifiedContentWidget);
                
                // 创建选项按钮
                QRadioButton *trueButton = new QRadioButton(u8"对", unifiedContentWidget);
                QRadioButton *falseButton = new QRadioButton(u8"错", unifiedContentWidget);
                
                trueButton->setStyleSheet("font-size: 10pt; padding: 5px 15px;");
                falseButton->setStyleSheet("font-size: 10pt; padding: 5px 15px;");
                
                buttonGroup->addButton(trueButton, 0);
                buttonGroup->addButton(falseButton, 1);
                
                optionsLayout->addWidget(trueButton);
                optionsLayout->addWidget(falseButton);
                optionsLayout->addStretch();
                
                // 如果有用户答案，设置选中状态
                QString userAnswer = judgeQuestion->userAnswer();
                if (userAnswer == u8"正确" || userAnswer == u8"对" || userAnswer == u8"true" || userAnswer == u8"1") {
                    trueButton->setChecked(true);
                } else if (userAnswer == u8"错误" || userAnswer == u8"错" || userAnswer == u8"false" || userAnswer == u8"0") {
                    falseButton->setChecked(true);
                }
                
                // 连接信号
                connect(trueButton, &QRadioButton::toggled, [judgeQuestion](bool checked) {
                    if (checked) {
                        judgeQuestion->setUserAnswer(u8"对");
                    }
                });
                
                connect(falseButton, &QRadioButton::toggled, [judgeQuestion](bool checked) {
                    if (checked) {
                        judgeQuestion->setUserAnswer(u8"错");
                    }
                });
                
                // 添加选项布局到主布局
                QWidget *optionsWidget = new QWidget(unifiedContentWidget);
                optionsWidget->setLayout(optionsLayout);
                optionsWidget->setStyleSheet("margin-left: 20px;");
                unifiedLayout->addWidget(optionsWidget);
            }
            
            // 添加题目间距
            unifiedLayout->addSpacing(20);
            judgeNum++;
        }
    }
    
    // 添加底部间距
    unifiedLayout->addSpacing(30);
    
    // 将统一内容容器添加到滚动区域的内容布局中
    m_contentLayout->addWidget(unifiedContentWidget);
    // 添加伸缩空间，确保内容不会被拉伸
    m_contentLayout->addStretch();
}

void MainWindow::clearDisplay()
{
    // 清空现有内容
    QLayoutItem *child;
    while ((child = m_contentLayout->takeAt(0)) != nullptr) {
        delete child->widget();
        delete child;
    }

    m_titleLabel->clear();
    m_studentLabel->clear();
}




void MainWindow::saveAnswers()
{
    if (!m_examPaper) {
        QMessageBox::warning(this, u8"警告", u8"没有加载试卷");
        return;
    }

    QString fileName = QFileDialog::getSaveFileName(this, u8"保存答案", u8"exam_answers.txt", u8"JSON文件 (*.json);;文本文件 (*.txt);;所有文件 (*.*)");
    if (fileName.isEmpty()) return;

    // 添加进度反馈
    QApplication::setOverrideCursor(Qt::WaitCursor);

    // 获取包含用户答案的JSON
    QJsonObject answerJson = m_examPaper->toJson();

    // 添加保存时间信息
    answerJson["saveTime"] = QDateTime::currentDateTime().toString(u8"yyyy-MM-dd hh:mm:ss");

    QJsonDocument doc(answerJson);
    QFile file(fileName);
    if (file.open(QIODevice::WriteOnly)) {
        file.write(doc.toJson(QJsonDocument::Indented));
        file.close();
        QApplication::restoreOverrideCursor();
        QMessageBox::information(this, u8"成功", u8"答案保存成功");
    } else {
        QApplication::restoreOverrideCursor();
        QMessageBox::critical(this, u8"错误", u8"保存文件失败: " + file.errorString());
    }
}



void MainWindow::updateAnswerStatus()
{
    int answeredCount = 0;
    int totalCount = m_examPaper->questions().size();
}


void MainWindow::clearAnswers()
{
    // 清空所有题目的用户答案
    if (m_examPaper) {
        for (Question *question : m_examPaper->questions()) {
            question->setUserAnswer("");
        }
        displayExam(); // 刷新界面
    }
}


void MainWindow::loadStyleSheet(const QString &path)
{
    QFile file(path);
    if (file.open(QIODevice::ReadOnly)) {
        QString styleSheet = QLatin1String(file.readAll());
        qApp->setStyleSheet(styleSheet);
        file.close();
    } else {
        qWarning() << u8"无法加载样式表:" << path << file.errorString();
    }
}




